#!/usr/bin/env node

const Koa = require('koa'),
      users= require('./routes/users.js'),
      bodyparser = require('koa-bodyparser'),
      tasks = require('./routes/tasks.js'),
      {JWT_KEY} = require('./lib/constant'),
      json = require('koa-json'),
      logger = require('koa-logger'),
      jwt = require('koa-jwt'),
      jwt2 = require('jsonwebtoken'),
      log = console.log;
const app = new Koa();

app.use(json());
app.use(logger());
app.use(jwt({secret: JWT_KEY}).unless({path: /\/api\/users\/login$/}));
app.use(bodyparser({enableTypes: ['json', 'form', 'text',]}));
app.use(async(ctx, next)=>{  // parse token user id
  // get token
  let token = ctx.header.authorization;
  if(typeof token !== 'undefined'){
    token = token.split(' ')[1];
    let user = jwt2.verify(token, JWT_KEY);
    console.log(user);
    ctx.userId = user.id;  //todo
  }

  await next();
});
app.use(tasks.routes());
app.use(users.routes());
app.listen(8080);
